package com.kt.thread.demo;

import java.util.HashMap;
import java.util.concurrent.Semaphore;


/**
 * Created by tangwy on 2016/1/20.
 */
public  class SemaphoreTest {

    public void test(){
        //只有三个信号灯，没有抢到的线程只能等别人释放信号灯
        final Semaphore semaphore=new Semaphore(3);
        for(int i=1;i<=10;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //获取信号灯
                        semaphore.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //availablePermits获取还有几个灯
                    System.out.println(Thread.currentThread().getName()+"进入,当前已有"+(3-semaphore.availablePermits())
                    +"个并发");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"即将离开");
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "已离开,当前还有" + (3 - semaphore.availablePermits())
                            + "个并发");
                }
            }).start();
        }
    }
}

